package org.grayrabbit.cms.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
	
	private static Logger LOG = LoggerFactory.getLogger(DateUtil.class);
	public static final int START_YEAR = 2011;
	/**
	 * @param date 日期
	 * @return 某一天的开始，例如：2010-05-12 00:00:00
	 */
	public static Date getDayStart(Date date) {
		if(date == null)  return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime();
	}
	
	/**
	 * @param date 日期
	 * @return 某一天的结束，例如：2010-05-12 23:59:59
	 */
	public static Date getDayEnd(Date date){
		if(date == null)  return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		return cal.getTime();
	}
	
	/**
	 * @param date  日期
	 * @param fomatReg  转换格式  例如："yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"
	 * @return  日期字符串
	 * @throws Exception
	 */
	public static String formatDateToString(Date date,String fomatReg){
		if(date == null || StringUtils.isBlank(fomatReg))  return null;
		SimpleDateFormat df = new SimpleDateFormat(fomatReg); 
		return df.format(date);
	}
	
	/**
	 * @param dateString 日期字符串"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"
	 * @param fomatReg 转换格式  例如："yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"
	 * @return 日期
	 * @throws Exception
	 */
	public static Date formatStringToDate(String  dateString,String fomatReg){
		if(StringUtils.isBlank(dateString) || StringUtils.isBlank(fomatReg))  return null;
		SimpleDateFormat df = new SimpleDateFormat(fomatReg); 
		Date date = null;
		try {
			date = df.parse(dateString);
		} catch (ParseException e) {
			LOG.error("字符串转日期异常", e);
			e.printStackTrace();
		}
		return date;
	}
  
	public static Date formatLongToDate(long time){	
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		return cal.getTime();
	}
	
	public static String formatLongToString(long time,String fomatReg){
		if(StringUtils.isBlank(fomatReg))  return null;
		Date date = formatLongToDate(time);
		return formatDateToString(date, fomatReg);
	}
	
	/**当前时间前  time ms的时间*/
	public static Date getDateEarlier(long time){		
		long now = System.currentTimeMillis();
		return formatLongToDate(now - time);
	}
	
	/** 当前时间与开始时间（2011）  相差几年 **/
	public static int getYearGap(){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date()); 
		return  cal.get(Calendar.YEAR)-START_YEAR;
	} 
}


